<template>
  <div class="sharingResourcesIndex" id="sharingResourcesIndex">
    <div class="sharingResourcesRight">
      <div class="select-content">
        <div class="select-item">
          <div class="title">文件类型：</div>
          <a-select v-model:value="resData.suffix" @change="changeType" :options="suffixOptions"
            class="titleSelect"></a-select>
        </div>
        <div class="select-item">
          <!-- <div class="title">共享时间：</div> -->
          <a-range-picker show-time v-model:value="timeValue" :valueFormat="valueFormat" @change="changeTime" />
        </div>
        <div class="select-item">
          <a-input v-model:value="resData.fileName" placeholder="搜索文件名需包含首字符
" @pressEnter="search" class="titleSelect" @blur="search" allow-clear>
            <template #suffix>
              <i class="iconfont icon-search" @click="search"></i>
            </template>
          </a-input>
        </div>
        <div class="option-content">
          <a-button @click="resetOptions">重置</a-button>
          <!-- <a-button :style="{ 'margin-left': '8px' }" class="addButton" type="primary" @click="search()">搜索</a-button> -->
        </div>
      </div>
      <treeTable :columns="columns.sharingResourcesColumns" :dataSource="resourcesData.records" :isSelect="true"
        :scroll="scroll" ref="tagBaseTables" :isShowPagination="isShowPagination" :showCheckDelete="showCheckDelete"
        :total="resourcesData.total" @changePage="changePage" align="middle">
        <template #bodyCell="{ column, text, record, index }">
          <template v-if="column.dataIndex === 'wjm'">
            <div class="titleBox">
              <div class="tabletypeImgBox">
                <a-image :src="record.url" :preview="{ visible: false }" @click="visible = true" class="tabletypeImg" />
                <div style="display: none">
                  <a-image-preview-group :preview="{
                    visible,
                    onVisibleChange: (vis: any) => (visible = vis),
                  }" class="opppqwq">
                    <a-image :src="record.url" />
                    <a-image :src="record.url" />
                    <a-image :src="record.url" />
                  </a-image-preview-group>
                </div>
              </div>
              <table-tool-tip :text="text" :column="column" class="titleTip">
                <span class="titleTip">{{ record.wjm }}</span>
              </table-tool-tip>
            </div>
          </template>
          <template v-if="column.dataIndex === 'resourceType'">
            <span>{{ getSourceType(record.resourceType) }}</span>
          </template>
          <template v-if="column.dataIndex === 'oparation'">
            <a class="eidtRecords" :class="{ disable: detailAble }" @click="detailsRecord(record)">详情</a>
            <a class="eidtRecords" :class="{ disable: downloadAble }" @click="downloadtemp(record)">下载</a>
          </template>
        </template>
        <template #otherOpration>
          <a-button :style="{ 'margin-left': '8px' }" :disabled="!rowSelection.length || downloadAble"
            @click="downloadtemp">下载</a-button>
        </template>
      </treeTable>
    </div>
  </div>
  <details1 v-if="isdetailsVisible" :isVisible="isdetailsVisible" @handleCancle="handleCancle" :detailData="detailData">
  </details1>
  <sharing v-if="issharingVisible" :isVisible="issharingVisible" @handleCancle="handleCancle"
    :resourcesIds="resourcesIds">
  </sharing>
</template>

<script lang="ts" setup>
import { ref, computed, watch, reactive, onMounted, nextTick, createVNode } from "vue";
import treeTable from "@/components/table/baseTable.vue";
import details1 from "./details.vue";
import sharing from "./sharing.vue";
import move from "./move.vue";
import { scrollType } from "@/type.d";
import { getTableScroll } from "@/components/table/tableConfig/table";
import columns from "@/components/table/tableConfig/tableColumn/systemTableColumn";
import tableToolTip from "@/components/table/tableToolTip.vue";
import { dataSourceType, detailDataItemType } from "@/type";
import { Modal, message } from "ant-design-vue";
import type { TreeProps } from "ant-design-vue";
import request from "@/api/index";
import globalFun from "@/utils/global";
import { utf8ToCh } from "@/utils/common"
import { routerPerm } from '@/utils/common';
// data
const detailAble = ref<boolean>(false);
const downloadAble = ref<boolean>(false);
let detailData = reactive<dataSourceType>({})
const tabsList = [
  {
    tabName: "内容列表",
    key: 1,
  },
  {
    tabName: "归档列表",
    key: 2,
  },
];
//树结构数据
const fieldNames = reactive<dataSourceType>({
  title: "groupName",
  key: "id",
});
const expandedKeys = ref<(string | number)[]>([]);
const gData = ref<TreeProps["treeData"]>();
const dataList: TreeProps["treeData"] = [];

const channelId = ref<number>();
const valueFormat = ref("YYYY-MM-DD HH:mm:ss");
const timeValue = ref<(string | number)[]>([]);
const isShowPagination = ref<boolean>(true); // 是否需要配分页器
const visible = ref<boolean>(false);
const showMenus = ref<boolean>(false);
const showCheckDelete = true; // 是否需要分页器中的自定义
const resourcesId = ref<string | number>(); //资源id
const resourcesIds = ref<(string | number)[]>([]); //资源id
const isdetailsVisible = ref<boolean>(false); //详情弹窗
const issharingVisible = ref<boolean>(false); //共享弹窗
let datas = reactive<dataSourceType>({});
const suffixOptions = ref<dataSourceType[]>([
  { label: "全部", value: null }
]);
const tagBaseTables = ref<any>({
  selectedRowKeys: [],
});
let rowSelection = ref<(string | number)[]>([]);
//表格数据
let resourcesData = reactive<dataSourceType>({ records: [], total: 0, });
let scroll: scrollType = reactive({ y: "", isFixed: false });
nextTick(() => {
  let obj = getTableScroll(74, "contentList", 132);
  scroll.y = obj.y;
  scroll.isFixed = obj.isFixed;
});
let resData: dataSourceType = ref({
  //头部筛选请求参数格式
  suffix: null,
  fileName: null,
  isShare: null,
  createTimeEnd: null,
  createTimeStart: null,
  pageNum: 1,
  pageSize: 10,
});
const typeOptions = [
  { label: "全部", value: null },
  { label: "是", value: 1 },
  { label: "否", value: 3 },
];
watch(
  () => tagBaseTables.value.selectedRowKeys,
  (newVal, oldVal) => {
    rowSelection.value = newVal;
  },
  { deep: true }
);
watch(() => resData.value.fileName, (newVal, oldVal) => {
  if (!newVal) {
    search()
  }

})
//获取栏目层级树列表
const fetchResourceGroupTreeList = async () => {
  // let params = {
  //   allPermFilter: true,
  //   siteId: userInfo.siteId,
  // };
  let data = await request.fetchResourceGroupTreeList();
  gData.value = data;
  dataList.push(...data);
};

// 根据分组获取资源库分页列表
const getResourceSharePageList = async () => {
  const params: dataSourceType = {
    shared: resData.isShare,
    startDate: resData.value.createTimeStart,
    endDate: resData.value.createTimeEnd,
    groupId: channelId.value,
    pageNumber: datas.pageNumber || 1,
    pageSize: datas.pageSize || 10,
    referenceIdList: '',
    resourceAlias: resData.value.fileName,
    suffix: resData.value.suffix
  }
  let data = await request.resourceSharePageList(params);
  resourcesData.records = data.records || [];
  resourcesData.total = data.total;
  nextTick(() => {
    let obj = getTableScroll(74, "myResourcesIndex", 150);
    scroll.y = obj.y;
    scroll.isFixed = obj.isFixed;
  });
}
const parentKey = ref<(string | number)[]>([]);
const getParentKey = (value: string | number, node: any) => {
  if (node.groupName.indexOf(value) > -1) {
    // parentKey = node.id;
    parentKey.value.push(node.id);
    if (node.children) {
      node.children.map((item: any) => {
        getParentKey(value, item);
      });
    }
  } else {
    if (node.children) {
      node.children.map((item: any) => {
        getParentKey(value, item);
      });
    }
  }
};

const traversal = (data: any) => {
  data.map((item: any) => {
    parentKey.value.push(item.id);
    if (item.children) {
      traversal(item.children);
    }
  });
  expandedKeys.value = parentKey.value;
};
// 打开详情弹窗
const detailsRecord = async (record: any) => {
  if (detailAble.value) return
  detailData = await request.resourceDetail({ id: record.id }) || {}
  nextTick(() => {
    isdetailsVisible.value = true;
  })
};

// 时间选择
const changeTime = (data: any) => {
  resData.value.createTimeStart = data ? data[0] : '';
  resData.value.createTimeEnd = data ? data[1] : '';
  search()

};
// 重置
const resetOptions = () => {
  timeValue.value = [];
  resData.value.fileName = null;
  resData.value.suffix = null;
  resData.value.createTimeEnd = null;
  resData.value.createTimeStart = null;
  search()
};
// 搜索



const search = () => {
  getResourceSharePageList()
};

// 文件类型即时搜索
const changeType = () => {
  search()
}

// 资源--文件类型筛选列表
const resourceFileTypeList = async () => {
  let data = await request.resourceFileTypeList() || [];
  // data.length && data.map((item: string) => {
  //   let obj = { label: item, value: item }
  //   suffixOptions.value.push(obj)
  // })
  let arr: any = Array.from(new Set(data))
  arr.length && arr.forEach((item: string) => {
    if (item) {
      let obj = { label: item, value: item }
      suffixOptions.value.push(obj)
    }
  })
}


//切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  datas = {
    pageNumber: data.pageCurrent,
    pageSize: data.pageSize,
  };
  getResourceSharePageList()
};


const downloadtemp = async (record: dataSourceType = {}) => {
  if (downloadAble.value) return
  // 下载资源库文件
  await request
    .resourceDownLoad({ ids: record.id ? [record.id] : rowSelection.value })
    .then((res: any) => {
      console.log(res, 9923213)
      globalFun.downloadFile(res, decodeURI(res['content-disposition']));
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
// 关闭弹窗
const handleCancle = () => {
  isdetailsVisible.value = false;
  issharingVisible.value = false;
};
const getSourceType = (type: any) => {
  let sourceType = type == 1 ? "图片" : type == 2 ? '视频' : type == 3 ? '音频' : type == 4 ? '附件' : '文档';
  return sourceType;
}
//onmounted
onMounted(async () => {
  routerPerm().includes('detailAble') ? detailAble.value = false : detailAble.value = true;
  routerPerm().includes('downloadAble') ? downloadAble.value = false : downloadAble.value = true;
  fetchResourceGroupTreeList();
  getResourceSharePageList();
  resourceFileTypeList()
});
</script>

<style lang="less" scoped>
.sharingResourcesIndex {
  width: 100%;
  // background: #fff;
  // padding-bottom: 24px;
  height: calc(100% - 56px);
  display: flex;
  background-color: #fff;
  padding: 16px;

  .icon-search {
    font-size: 14px !important;
  }

  .side-left {
    width: 216px;
    height: calc(100% - 24px);
    border-right: 1px solid rgba(0, 0, 0, 0.06);
    padding-right: 4px;
    position: relative;
    transition: width 0.3s;
    padding-right: 24px;

    .res-tree-menus {
      margin: 0;
      background: #fff;
      z-index: 44;
      position: absolute;
      list-style-type: none;
      min-width: 130px;
      padding: 5px 0;
      box-sizing: border-box;
      border-radius: 4px;
      box-shadow: 0px -3px 16px 0px rgba(89, 155, 255, 0.15);

      li {
        margin: 0;
        padding: 0 20px;
        cursor: pointer;
        font-size: 14px;
        font-weight: 400;
        line-height: 32px;
        color: rgba(0, 0, 0, 0.85);

        &:hover {
          background: rgba(0, 0, 0, 0.04);
        }
      }
    }

    .treeBox {
      height: 100%;
    }

    .treeTitle {
      margin-top: 16px;
      margin-bottom: 4px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 24px;
      background: #edf7ff;
      border-radius: 2px;
      padding: 0 4px;

      .openorclose {
        cursor: pointer;
        display: flex;
        align-items: center;
      }
    }

    .open-right {
      position: absolute;
      top: 50%;
      right: -1px;
      margin-top: -15px;
      bottom: -20px;
      height: 30px;
      width: 20px;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
      background: #ffffff;
      border: 1px solid rgba(0, 0, 0, 0.06);
      z-index: 2;
    }

    .open-right-side {
      right: -20px;
    }

    .iconfont:hover {
      color: rgba(0, 0, 0, 0.6);
    }

    .iconfonts {
      color: rgba(0, 0, 0, 0.45);
    }
  }

  .side-close {
    width: 0;
    transition: width 0.3s;

    .treeBox {
      display: none;
    }
  }

  .sharingResourcesRight {
    width: 500px;
    flex: 1;
    height: 100%;

    .addButton {
      display: flex;
      align-items: center;
      margin-right: 8px;

      .iconadd {
        font-size: 24px;
        margin-right: 4px;
      }
    }

    .select-content {
      margin-top: 24px;
      background: rgba(0, 0, 0, 0.02);
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      padding: 24px 24px 0;

      // margin-bottom: 24px;
      //   .selectLeft {
      //     display: flex;
      //     flex-direction: row;
      //     justify-content: space-between;
      //     align-items: center;
      //     flex-wrap: wrap;
      //     flex: 1;
      //   }
      .select-item {
        // width: 354px;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: flex-end;
        margin-bottom: 24px;

        .title {
          font-size: 14px;
          font-family: PingFang SC-Regular, PingFang SC;
          font-weight: 400;
          color: rgba(0, 0, 0, 0.85);
        }

        .titleSelect {
          width: 205px;
          margin-right: 12px;
        }
      }

      .option-content {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: flex-end;
        margin-bottom: 24px;
      }

      .option-content .openorclose {
        display: flex;
        flex-direction: row;
        align-items: center;
        margin-left: 16px;
        font-size: 14px;
        font-family: PingFang SC-Regular, PingFang SC;
        font-weight: 400;
        color: #1f6ded;

        .iconfont {
          margin-left: 5px;
        }
      }
    }
  }




  .eidtRecords {
    margin-right: 16px;
  }

  .eidtRecords:last-child {
    margin-right: 0;
  }

  ::v-deep(.titleBox) {
    display: flex;
    align-items: center;
    justify-items: center;

    // height: 29px;
    // line-height: 29px;
    // height: 18px;
    .titleTip {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      margin-left: 16px;
    }

    .tabletypeImgBox {
      width: 80px;
      height: 80px;
      padding: 8px;
      background: #ffffff;
      border-radius: 2px;
      border: 1px solid rgba(0, 0, 0, 0.15);
    }

    .tabletypeImg {
      max-width: 64px;
      width: auto;
      max-height: 64px;

      height: auto;
      margin: auto;
      //   width: 16px;
      //   height: 16px;
      // line-height: 18px;
    }
  }

  ::v-deep(.ant-table-cell) {
    vertical-align: middle;
  }

  ::v-deep(.ant-table-cell:nth-last-of-type(1)) {
    text-align: right;
  }
}

.disable {
  color: rgba(0, 0, 0, 0.25);
  cursor: not-allowed;
}

.contentIndexLeft {
  padding-right: 24px;
  width: 216px;
  height: 100%;
}

::v-deep(::-webkit-scrollbar) {
  height: 10px;
}

::v-deep(.side-left .ant-tree-list-holder) {
  width: auto;
  height: 100%;
  transition: width 0.3s;
}

::v-deep(.side-close .ant-tree-list-holder) {
  width: 0;
  height: 100%;
  transition: width 0.3s;
}

::v-deep(.side-left .ant-tree-list:hover .ant-tree-list-scrollbar) {
  display: block !important;
}

::v-deep(.ant-tree-list .ant-tree-list-scrollbar) {
  display: none !important;
}

::v-deep(.ant-tree-list-scrollbar-thumb) {
  background: rgba(0, 0, 0, 0.15) !important;
}

::v-deep(.ant-checkbox + span) {
  padding-left: 12px;
  padding-right: 0;
}

::v-deep(.ant-table-wrapper) {
  margin-top: 24px;
}

::v-deep(.ant-table-thead > tr > th) {
  // padding: 16px 0 16px 16px;
}

table tr th.ant-table-selection-column,
table tr td.ant-table-selection-column {
  padding-right: 8px;
  padding-left: 8px;
  text-align: left;
}
</style>
<style lang="less">
.side-left {
  .ant-input-search {
    margin-top: 16px;
  }

  .ant-tree {
    height: calc(100% - 88px);
    overflow: auto;

    .ant-tree-treenode {
      width: 100%;

      .ant-tree-node-content-wrapper {
        width: 100%;
      }
    }

    .ant-tree::-webkit-scrollbar {
      display: none;
    }

    .ant-tree:hover::-webkit-scrollbar {
      display: block;
    }

    .ant-tree-list-scrollbar-thumb {
      height: auto !important;
    }

    .ant-tree-list-holder {
      overflow-y: unset !important;
    }
  }
}

.ant-image-preview-img-wrapper {

  // left: 50%;
  // transform: translateX(-50%);
  img {
    display: inline-block;
  }
}
</style>
